package work.flow.demo.api;

import org.flowable.engine.IdentityService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LeaveProcessApi_v5 {

    @Qualifier("LeaveProcessEngine")
    private final ProcessEngine processEngine;

    public LeaveProcessApi_v5(ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    //添加采集员组
    @GetMapping("/v5_01")
    public String get01(@RequestParam Map<String, String> params) {
        //参数-发起人
        String userId = params.get("userId");

        if (userId == null || userId.isEmpty()) {
            return "请输入用户ID";
        }
        IdentityService identityService = processEngine.getIdentityService();
        // 1、创建用户组,user_g和bpmn文件中的组对应，
        //创建组，BPMN流程定义中使用了 student_group 作为候选组，但这并不会自动在Flowable的身份服务中创建实际的组
        Group existingGroup = identityService.createGroupQuery().groupId("gather_group").singleResult();
        if (existingGroup == null) {
            Group starterGroup = identityService.newGroup("gather_group");
            starterGroup.setName("采集员组");
            identityService.saveGroup(starterGroup);
        }
        // 2、检查用户是否在授权组中
        boolean isAuthorized = identityService.createGroupQuery()//
                .groupMember(userId)//
                .groupId("gather_group")//
                .count() > 0;//
        if (isAuthorized) {
            return "该用户已加入采集员组，请不要重复添加";
        } else {
            //创建用户
            User newUser = identityService.newUser(userId);
            identityService.saveUser(newUser);
            // 将用户加入组
            identityService.createMembership(userId, "gather_group");
            return "该用户已加入采集员组-" + userId;
        }
    }

    //添加受理员组
    @GetMapping("/v5_02")
    public String get02(@RequestParam Map<String, String> params) {
        //参数-发起人
        String userId = params.get("userId");

        if (userId == null || userId.isEmpty()) {
            return "请输入用户ID";
        }
        IdentityService identityService = processEngine.getIdentityService();
        // 1、创建用户组,user_g和bpmn文件中的组对应，
        //创建组，BPMN流程定义中使用了 student_group 作为候选组，但这并不会自动在Flowable的身份服务中创建实际的组
        Group existingGroup = identityService.createGroupQuery().groupId("acceptance_group").singleResult();
        if (existingGroup == null) {
            Group starterGroup = identityService.newGroup("acceptance_group");
            starterGroup.setName("采集员组");
            identityService.saveGroup(starterGroup);
        }
        // 2、检查用户是否在授权组中
        boolean isAuthorized = identityService.createGroupQuery()//
                .groupMember(userId)//
                .groupId("acceptance_group")//
                .count() > 0;//
        if (isAuthorized) {
            return "该用户已加入受理员组，请不要重复添加";
        } else {
            //创建用户
            User newUser = identityService.newUser(userId);
            identityService.saveUser(newUser);
            // 将用户加入组
            identityService.createMembership(userId, "acceptance_group");
            return "该用户已加入受理员组-" + userId;
        }
    }

    //发起案件流程
    @GetMapping("/v5_03")
    public String get03(@RequestParam Map<String, String> params) {
        //参数-发起人
        String userId = params.get("userId");

        if (userId == null || userId.isEmpty()) {
            return "请输入用户ID";
        }

        // 1、检查用户是否在授权组中
        IdentityService identityService = processEngine.getIdentityService();
        boolean isAuthorized = identityService.createGroupQuery()//
                .groupMember(userId)//
                .groupId("gather_group")//
                .count() > 0;//
        if (!isAuthorized) {
            return "该用户没有授权请假流程";
        }

        //2、获取流程实例
        RuntimeService runtimeService = processEngine.getRuntimeService();

        //3、发起流程,businessK业务id不可变
        String processId = "Process_167wkwb";//对应bpmn文件中的process id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processId);
        //处理任务
        String processInstanceId = processInstance.getId();  // 获取流程实例ID
        TaskService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery()//
                .processInstanceId(processInstanceId)//流程id
                .taskCandidateUser(userId)//根据候选用户id查询任务
                .list();
        if (!tasks.isEmpty()) {
            for (Task task : tasks) {
                System.out.println("开始遍历---");
                System.out.println("需先完成任务: " + task.getId());
                Map<String, Object> variables = new HashMap<>();
                variables.put("initiator", userId);//发起人->用于查询谁发起的请假
                variables.put("leave", "5");//请假天数
                variables.put("reason", "去旅游");//请假理由
                variables.put("assignee", "wangwu");//指定下一环节处理人id
                variables.put("action_type", "acceptance");//指定下一节点流向
                //用时间做业务businessKey
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                String businessKey = formatter.format(date);
                variables.put("businessKey", businessKey);
                //过滤只属于当前用户的任务
                taskService.complete(task.getId(), variables);//流程继续流程
            }
        }
        return "用户：" + userId + "发起成功" + processInstance.getId();
    }

    //受理员查询任务
    @GetMapping("/v5_05")
    public String get05(@RequestParam Map<String, String> params) {
        //参数-发起人
        String userId = params.get("userId");

        if (userId == null || userId.isEmpty()) {
            return "请输入用户ID";
        }

        //2、获取流程实例
        RuntimeService runtimeService = processEngine.getRuntimeService();

        //查询该用户当前的任务
        TaskService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery()//
                .taskCandidateUser(userId)//根据候选用户id查询任务
                .list();
        System.out.println("共有：" + tasks.size() + "个任务");
        if (!tasks.isEmpty()) {
            for (Task task : tasks) {
                System.out.println("开始遍历---");
                System.out.println("需先完成任务: " + task.getName());
                Map<String, Object> processVariables = taskService.getVariables(task.getId());
                String assignee = (String) processVariables.get("assignee");
                System.out.println("assignee: " + assignee);
//                //过滤只属于当前用户的任务
//                if (assignee.equals("wangwu")) {
//                    System.out.println("assignee: " + assignee);
//                    System.out.println("找到任务: " + task.getId());
//                    Map<String, Object> variables = new HashMap<>();
//                    variables.put("action_type", "rejection");//驳回操作
//                    taskService.complete(task.getId(), variables);//流程继续流程
//                }
            }
        }
        return "用户：" + userId + "处理请假成功";
    }


    //受理员查询任务
    @GetMapping("/v5_04")
    public String get06(@RequestParam Map<String, String> params) {
        //参数-发起人
        String userId = params.get("userId");

        if (userId == null || userId.isEmpty()) {
            return "请输入用户ID";
        }

        //2、获取流程实例
        RuntimeService runtimeService = processEngine.getRuntimeService();

        //查询该用户当前的任务
        TaskService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery()//
                .taskCandidateUser(userId)//根据候选用户id查询任务
                .list();
        System.out.println("共有：" + tasks.size() + "个任务");
        if (!tasks.isEmpty()) {
            for (Task task : tasks) {
                System.out.println("开始遍历---");
                System.out.println("需先完成任务: " + task.getName());
                Map<String, Object> processVariables = taskService.getVariables(task.getId());
                String assignee = (String) processVariables.get("assignee");
                System.out.println("assignee: " + assignee);
                //过滤只属于当前用户的任务
                if (assignee.equals("wangwu")) {
                    System.out.println("assignee: " + assignee);
                    System.out.println("找到任务: " + task.getId());
                    Map<String, Object> variables = new HashMap<>();
                    variables.put("action_type", "rejection");//驳回操作
                    taskService.complete(task.getId(), variables);//流程继续流程
                }
            }
        }
        return "用户：" + userId + "处理请假成功";
    }

}
